package com.corpgovernment.organization.service;

import com.corpgovernment.api.messageadvice.enums.MsgBizType;
import com.corpgovernment.api.messageadvice.vo.MessageVo;
import com.corpgovernment.common.apollo.BasicManageApollo;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.organization.producer.MessageEventProducer;
import com.corpgovernment.organization.producer.MultiTenantSendMessageProducer;
import com.corpgovernment.redis.cache.RedisUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

import static com.corpgovernment.api.basic.metadata.ELoginStatus.MSGCODE_INCORRECT;
import static com.corpgovernment.api.basic.metadata.ELoginStatus.MSGCODE_INVALID;

/**
 * MsgService
 *
 * @author jhxue
 */
@Component
@Slf4j
public class MsgService {
	/**
	 * 短信模板变量名
	 */
	public static final String TEMPLATE_VARIABLE_CODE_NAME = "code";
	public static final String TEMPLATE_VARIABLE_PASSWORD_NAME = "password";
	/**
	 * 大陆国际区号
	 */
	private static final String CHINA_MAINLAND_AREA_CODE = "86";
	/**
	 * 大陆手机号长度
	 */
	private static final int CHINA_MAINLAND_PHONE_LENGTH = 11;
	/**
	 * 每个变量的长度限制为1~20字符
	 */
	private static final int PARAM_LENGTH = 20;

	/**
	 * 短信服务
	 */
	@Autowired
	private MessageEventProducer messageEventProducer;
	/**
	 * 缓存处理
	 */
	@Autowired
	private RedisUtils redisUtils;

	/**
	 * @param bizType     消息模板枚举
	 * @param params      模板参数和值
	 * @param phone       手机号
	 * @param countryCode 国际区号
	 * @return 发送结果
	 */
	public boolean sendAliyunTemplateMsg(MsgBizType bizType, Map<String, Object> params,
										 @NonNull String phone, @NonNull String countryCode) {
		messageEventProducer.sendMessageEvent(bizType,countryCode,phone,params);
		return true;
	}

	/**
	 * 验证短信验证码
	 *
	 * @param key     原始验证码key
	 * @param msgCode 待验证的验证码
	 * @param source  登录来源
	 */
	public void validateMsgCode(String key, String msgCode, String source) {
		String originCode = redisUtils.getCache(key, String.class);
		log.info("validateMsgCode({},{},{})", key, msgCode, source);
		// 验证码失效
		if (StringUtils.isBlank(originCode)) {
			throw new CorpBusinessException(MSGCODE_INVALID.getValue(), MSGCODE_INVALID.getDesc());
		}
		// 验证码不正确
		if (!StringUtils.equals(msgCode, originCode, false)) {
			throw new CorpBusinessException(MSGCODE_INCORRECT.getValue(), MSGCODE_INCORRECT.getDesc());
		}
		// 验证码校验通过删除验证码
		redisUtils.delete(key);
	}

	/**
	 * 是否发送短信
	 *
	 * @return 是否
	 */
	private static boolean isRealSend() {
		return BasicManageApollo.getZtSmsSend();
	}
}
